/*
 * Copyright (c) 2012-2014, EpicSaaS Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package com.epicsaas.app.ksdapp.util;

import java.util.Date;
import java.util.Random;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;

public class TestUtil {

    /**
     * 
     * 
    protected function generateSalt($cost=10)
    {
    	if(!is_numeric($cost)||$cost<4||$cost>31){
    		throw new CException(Yii::t('Cost parameter must be between 4 and 31.'));
    	}
    	// Get some pseudo-random data from mt_rand().
    	$rand='';
    	for($i=0;$i<8;++$i)
    		$rand.=pack('S',mt_rand(0,0xffff));
    	// Add the microtime for a little more entropy.
    	$rand.=microtime();
    	// Mix the bits cryptographically.
    	$rand=sha1($rand,true);
    	// Form the prefix that specifies hash algorithm type and cost parameter.
    	$salt='$2a$'.str_pad((int)$cost,2,'0',STR_PAD_RIGHT).'$';
    	// Append the random salt string in the required base64 format.
    	$salt.=strtr(substr(base64_encode($rand),0,22),array('+'=>'.'));
    	return $salt;
    }
     * 
     * 
     * @param cost
     * @return
     */

    public static String generateSalt(int cost) {
        String salt = "$2a$10$", rand = "";

        for (int i = 0; i < 8; i++) {
            rand += hexToString(new Random().nextInt(0xffff) + "");
        }
        rand += new Date().getTime();
        rand = new String(HmacSHA1(rand));
        String t = new sun.misc.BASE64Encoder().encode(rand.getBytes()).substring(0, 22);

        salt += t.replace("+", ".");

        return salt;
    }

    public static String toStringHexTest(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static byte[] str2pack(String str) {
        int nibbleshift = 4;
        int position = 0;
        int len = str.length() / 2 + str.length() % 2;

        byte[] output = new byte[len];
        for (char v : str.toCharArray()) {
            byte n = (byte) v;
            if (n >= '0' && n <= '9') {
                n -= '0';
            } else if (n >= 'A' && n <= 'F') {
                n -= ('A' - 10);
            } else if (n >= 'a' && n <= 'f') {
                n -= ('a' - 10);
            } else {
                continue;
            }

            output[position] |= (n << nibbleshift);

            if (nibbleshift == 0) {
                position++;
            }
            nibbleshift = (nibbleshift + 4) & 7;
        }

        return output;
    }

    public static byte[] hexToString(String hex) {
        // hexToString that works at a byte level, not a character level
        byte[] output = new byte[(hex.length() + 1) / 2];
        for (int i = hex.length() - 1; i >= 0; i -= 2) {
            int from = i - 1;
            if (from < 0) {
                from = 0;
            }
            String str = hex.substring(from, i + 1);
            output[i / 2] = (byte) Integer.parseInt(str, 16);
        }
        return output;
    }

    public static byte[] HmacSHA1(String post) {
        //定义加密算法
        try {
            String Algorithm = "HmacSHA1";
            // Generate secret key for HMAC-SHA1
            KeyGenerator kg = KeyGenerator.getInstance(Algorithm);
            SecretKey sk = kg.generateKey();
            // Get instance of Mac object implementing HMAC-SHA1, and
            // initialize it with the above secret key
            Mac mac = Mac.getInstance(Algorithm);
            mac.init(sk);
            byte[] result = mac.doFinal(post.getBytes());

            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(generateSalt(10));
    }

}
